package com.cnswhy.cloud.server.core.shop;

import com.cnswhy.cloud.common.core.exception.BizException;
import com.cnswhy.cloud.common.redis.annotation.RedisLock;
import com.cnswhy.cloud.common.redis.model.LockTimeoutStrategy;
import com.cnswhy.cloud.server.core.entity.ShopProductStock;
import com.cnswhy.cloud.server.core.service.shop.ShopProductStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ProductStockService {
    @Autowired
    ShopProductStockService shopProductStockService;

    private ShopProductStock getShopProductStock(Long stockId) throws BizException{
        ShopProductStock shopProductStock = shopProductStockService.getById(stockId);
        if(shopProductStock == null){
            throw new BizException("商品库存不存在");
        }
        return shopProductStock;
    }
    @RedisLock(name = "ShopProductStock", waitTime = 10,leaseTime = 60,keys = {"#stockId"},lockTimeoutStrategy = LockTimeoutStrategy.FAIL_FAST)
    public void addStock(Long stockId,Long stock) throws BizException{
        ShopProductStock shopProductStock = getShopProductStock(stockId);
        shopProductStock.setStock(shopProductStock.getStock() + stock);
        shopProductStockService.updateById(shopProductStock);
    }
    @RedisLock(name = "ShopProductStock", waitTime = 10,leaseTime = 60,keys = {"#stockId"},lockTimeoutStrategy = LockTimeoutStrategy.FAIL_FAST)
    public void subStock(Long stockId,Long stock) throws BizException{
        ShopProductStock shopProductStock = getShopProductStock(stockId);
        shopProductStock.setStock(shopProductStock.getStock() - stock);
        if(shopProductStock.getStock().compareTo(Long.valueOf(0L)) < 0){
            throw new BizException("抱歉，库存不足");
        }
        shopProductStockService.updateById(shopProductStock);
    }
}
